package com.beermanager.activities;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.beermanager.domain.Bar;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class PersistenceManager {
    private Context mContext;

    public PersistenceManager(Context mContext) {
        this.mContext = mContext;
    }

    public void storeBar(Bar bar) {
    	try {
			FileOutputStream file = mContext.openFileOutput("barsList", Context.MODE_APPEND);
			
			file.write((bar.getName() + "\n").getBytes());
			file.write((bar.getAddress() + "\n").getBytes());
			file.write((bar.getCity() + "\n").getBytes());
			file.write((bar.getCountry() + "\n").getBytes());
			
	    	if(bar.getPicture() != null) {
	    		file.write(storeBitmap(bar.getPicture(), bar.getName() + "_picture.png").getBytes());
	    	}
	    	
			file.write(("\n").getBytes());
			
			file.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    public void clearBarList() {
    	mContext.deleteFile("barsList");
    }
    
    public ArrayList<Bar> getBarsList() {
    	ArrayList<Bar> bars = new ArrayList<Bar>();
    	
    	try {
			FileInputStream file = mContext.openFileInput("barsList");
			InputStreamReader streamReader = new InputStreamReader(file);
			BufferedReader buffReader = new BufferedReader(streamReader);
			
			String barName = buffReader.readLine();
			
			while(barName != null) {
				Bar bar = new Bar(barName);
				bar.setAddress(buffReader.readLine());
				bar.setCity(buffReader.readLine());
				bar.setCountry(buffReader.readLine());
				String pictureAddress = buffReader.readLine();
				// se tiver endereço da imagem
		    	if(pictureAddress.length() != 0) {
		    		Bitmap bitmap = BitmapFactory.decodeFile(pictureAddress);
		    		bar.setPicture(bitmap);
		    	}
		    	
		    	barName = buffReader.readLine();
		    	
		    	bars.add(bar);
			}
			
			file.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    	
    	
    	return bars;
    }
    
    private String storeBitmap(Bitmap bitmap, String filename) {
    	try {
    	       FileOutputStream out = mContext.openFileOutput(filename, Context.MODE_WORLD_WRITEABLE);
    	       bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
    	       out.close();
    	} catch (Exception e) {
    	       e.printStackTrace();
    	}
    	
    	return mContext.getFileStreamPath(filename).getAbsolutePath();
    }
}
